/**
 * 
 */
package ar.com.greensoft.neosystem.model.constraint;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;

import ar.com.greensoft.neosystem.model.PersonaJuridica;

/**
 * 
 * @author Jorge E. Villaverde
 * @since 23/01/2012
 * @version 1.0.0
 */
public class PersonaJuridicaContraintsValidator implements ConstraintValidator<PersonaJuridicaContraints, PersonaJuridica> {

	private static final String PERSONA_JURIDICA_INVALID_CUIT_MESSAGE = "{ar.com.greensoft.neosystem.crm.model.PersonaJuridica.cuit.message}";

	@Override
	public void initialize(PersonaJuridicaContraints constraintAnnotation) {
	}

	@Override
	public boolean isValid(PersonaJuridica value, ConstraintValidatorContext context) {
		boolean isValid = false;
		boolean cuitPersonaJuridica = false;
		
		if(value == null)
			return false;
		if(value.getCuit() == null)
			return false;
		
		String type = value.getCuit().substring(0, 2);
		try{
			Integer nType = Integer.parseInt(type);
			if((nType == 30)){
				cuitPersonaJuridica = true;
			}
		}catch (NumberFormatException ne){
		}		
				
		isValid = cuitPersonaJuridica;
		
        if(!isValid) {
        	context.disableDefaultConstraintViolation();
        	context.buildConstraintViolationWithTemplate(
        			PERSONA_JURIDICA_INVALID_CUIT_MESSAGE)
        			.addNode("cuit")
        			.addConstraintViolation();
        }
				
        return isValid;
	}

}
